package com.yijdn.common.config;

import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.yijdn.common.utils.HttpContextUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author zww
 * @date 2018-03-25 11:19
 * <p>
 * Email 971762302@qq.com
 * <p>
 * Describe:
 */
@Configuration
@EnableAutoConfiguration
@MapperScan("com.yijdn.*.mapper")
public class LocaleConfig extends WebMvcConfigurerAdapter {

    /**
     * 分页插件
     * @return
     */
    @Bean
    public Pagination pagination(){
        Pagination pagination = new Pagination();
        return pagination;
    }


    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        Locale locale = Locale.CHINA;
        /*HttpServletRequest request = HttpContextUtils.getRequest();
        String lang = request.getParameter("lang");
        if(!StringUtils.isEmpty(lang)){
            try {
                locale=new Locale(lang);
            } catch (NullPointerException e){}

        }*/
        // 默认语言
        slr.setDefaultLocale(locale);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();

        // 参数名
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}
